<template>
  <div class="bigbox">
    <div class="top">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        label-position="right"
        label-width="70px"
        onsubmit="return false"
      >
        <el-col :span="5">
          <el-form-item label="用电企业">
            <el-select
              style="width: 100%"
              v-model="form.companyId"
              placeholder="请选择"
              @change="companyChange"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部门">
            <el-select
              style="width: 100%"
              v-model="form.departmentId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.departmentName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: left; padding-left: 20px">
          <el-radio-group v-model="radio" style="margin-right: 20px">
            <el-radio-button label="月"></el-radio-button>
            <el-radio-button label="年"></el-radio-button>
          </el-radio-group>
          <el-date-picker
            style="width: 200px; height: 40px; line-height: 40px"
            v-model="date"
            :type="
              this.radio == '日'
                ? 'date'
                : this.radio == '月'
                ? 'month'
                : 'year'
            "
            :format="
              this.radio == '日'
                ? 'yyyy-MM-dd'
                : this.radio == '月'
                ? 'yyyy-MM'
                : 'yyyy'
            "
            placeholder="选择时间"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-form-item>
            <div>
              <button
                @click="chongzhi"
                class="button"
                style="margin-right: 5px"
              >
                重置
              </button>
              <button @click="chaxun" class="button chaxun">查询</button>
            </div>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <div class="nhde">
      <div class="left">
        <div class="tit">
          <div class="title">能耗定额</div>
          <div class="mes">
            <div class="m">
              <div class="color color1"></div>
              <div>正常</div>
            </div>
            <div class="m">
              <div class="color color2"></div>
              <div>超标</div>
            </div>
          </div>
        </div>
        <el-calendar
          v-loading="loading1"
          :range="[startDate, endDate]"
          v-if="radio === '月' && show"
        >
          <template slot="dateCell" slot-scope="{ date }">
            <el-tooltip placement="top" effect="light">
              <div slot="content">
                日期:{{ dateSet("YYYY-MM-DD", date) }}<br />电量:{{
                  EnergyData.find(
                    (i) => i.timeReading == dateSet("YYYY-MM-DD", date)
                  )?.usageValue || "-"
                }}
              </div>
              <div class="dateCell" @click="getLine(date)">
                <!-- {{ data.day.split("-").slice(1).join("-") }} -->
                <!-- {{ data.day.split("-").slice(1).join("-") }} -->
                <!-- EnergyData -->
                <div :class="findDate(date)">
                  <!-- {{ dateSet("D", date) }} -->
                  <!-- {{ dateSet("D", date) }} -->
                  {{
                    EnergyData.find(
                      (i) => i.timeReading == dateSet("YYYY-MM-DD", date)
                    )?.usageValue || "-"
                  }}
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-calendar>
        <div class="box" v-loading="loading1" v-else>
          <div
            class="box-item"
            v-for="(month, index) in months"
            style="cursor: pointer"
            :key="index"
            @click="getLine(getYearmonth(month.value))"
          >
            <el-tooltip placement="top" effect="light">
              <div slot="content">
                日期:{{ dateSet("YYYY-MM-DD", date) }}<br />电量:{{
                  EnergyData.find(
                    (i) => i.timeReading == getYearmonth(month.value)
                  )?.usageValue || "-"
                }}
              </div>
              <div
                class="box-items"
              >
                <span :class="findMonth(getYearmonth(month.value))">
                  {{
                  EnergyData.find(
                    (i) => i.timeReading == getYearmonth(month.value)
                  )?.usageValue || "-"
                }}
                </span>
              </div>
            </el-tooltip>
          </div>
        </div>
        <div></div>
      </div>
      <div class="right">
        <div
          v-loading="loading2"
          id="nhde"
          style="width: 100%; height: 100%"
        ></div>
      </div>
    </div>
    <div class="nhzb">
      <div class="toptit">
        <div class="title">能耗指标</div>
        <div class="radio">
          <el-radio :value="1" :label="1">单位面积能耗</el-radio>
        </div>
      </div>
      <div class="bar">
        <div
          v-loading="loading3"
          id="nhzb"
          style="width: 100%; height: 90%"
        ></div>
      </div>
      <div class="bartable">
        <el-table
          v-loading="loading4"
          :data="tableList"
          style="width: 99%"
          height="23vh"
          border
          ref="table"
          :header-cell-style="{
            background: '#f5f5f5',
            'text-align': 'center',
          }"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column align="center" prop="dateTime" label="日期">
          </el-table-column>
          <el-table-column prop="departmentName" label="部门">
          </el-table-column>
          <el-table-column
            align="right"
            prop="areaAvgValue"
            label="单位面积能耗(kWh/㎡)"
          >
          </el-table-column>
          <el-table-column
            align="right"
            prop="areaAvgReasonableValue"
            label="合理值(kWh/㎡)"
          >
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getCompanyListApi } from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import {
  getDepartmentListApi,
  getEnergyDataApi,
  getEnergyLineApi,
  getEnergyZBLineApi,
  getEnergyZBListApi
} from '@/api/energy-consumption/Department/Examine'
import dayjs from 'dayjs'
export default {
  name: 'DepartmentExamine',
  data () {
    return {
      form: {},
      companyList: [],
      departmentList: [],
      radio: '月',
      date: null,
      value: new Date(),
      EnergyData: [],
      Linelist: [],
      ZBLinelist: [],
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      tableList: [],
      months: [
        { name: '一月', value: '01' },
        { name: '二月', value: '02' },
        { name: '三月', value: '03' },
        { name: '四月', value: '04' },
        { name: '五月', value: '05' },
        { name: '六月', value: '06' },
        { name: '七月', value: '07' },
        { name: '八月', value: '08' },
        { name: '九月', value: '09' },
        { name: '十月', value: '10' },
        { name: '十一月', value: '11' },
        { name: '十二月', value: '12' }
      ],
      show: false,
      startDate: '',
      endDate: ''
    }
  },
  watch: {
    radio: {
      handler (newValue) {
        if (this.radio === '月') {
          this.date = dayjs().format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs().format('YYYY')
        }
      },
      immediate: true
    },
    date: {
      handler (newValue) {
        this.show = false
        if (this.radio === '月') {
          this.date = dayjs(newValue).format('YYYY-MM')
          const { s, e } = this.getStartAndEndDate(this.date)
          this.startDate = s
          this.endDate = e
        } else if (this.radio === '年') {
          this.date = dayjs(newValue).format('YYYY')
        }
        this.$forceUpdate()
        this.$nextTick(() => {
          this.show = true
        })
      },
      immediate: true,
      deep: true
    }
  },
  async created () {
    await this.getCompanyList()
    await this.getDepartmentList()
    this.getdatalist()
  },
  methods: {
    // 获取用电企业列表
    async getCompanyList () {
      const res = await getCompanyListApi()
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find(i => i.id == companyId)) {
        this.$set(this.form, 'companyId', companyId)
      } else {
        this.$set(this.form, 'companyId', this.companyList[0].id)
      }
    },
    companyChange (val) {
      if (val) {
        localStorage.setItem('companyId', val)
      }
      this.getDepartmentList()
    },
    getYearmonth (month) {
      return this.date + '-' + month
    },
    // 处理日历时间
    getStartAndEndDate (dateString) {
      const date = dayjs(dateString)
      const firstDayOfMonth = date.startOf('month')
      const lastDayOfMonth = date.endOf('month')

      const startRange = firstDayOfMonth.subtract(
        firstDayOfMonth.day() - 1,
        'day'
      )
      const endRange = lastDayOfMonth.add(7 - lastDayOfMonth.day(), 'day')

      return {
        s: startRange.format('YYYY-MM-DD'),
        e: endRange.format('YYYY-MM-DD')
      }
    },
    findDate (date) {
      return this.EnergyData.find(
        (i) => i.timeReading == this.dateSet('YYYY-MM-DD', date)
      )?.valueReading === '超标'
        ? 'one'
        : this.EnergyData.find(
          (i) => i.timeReading == this.dateSet('YYYY-MM-DD', date)
        )?.valueReading === '正常'
          ? 'two'
          : 'thr'
    },
    findMonth (date) {
      return this.EnergyData.find((i) => i.timeReading == date)
        ?.valueReading === '超标'
        ? 'one'
        : this.EnergyData.find((i) => i.timeReading == date)?.valueReading ===
          '正常'
          ? 'two'
          : 'thr'
    },
    dateSet (type, val) {
      if (type === 'YYYY-MM-DD') {
        return dayjs(val).format('YYYY-MM-DD')
      } else if (type === 'D') {
        return dayjs(val).format('D')
      }
    },
    // 部门下拉
    async getDepartmentList () {
      const res = await getDepartmentListApi({
        companyId: this.form.companyId,
        pageNo: 0,
        pageSize: 1000
      })
      this.departmentList = res.data.list
      this.$set(this.form, 'departmentId', this.departmentList[0].id)
    },
    // 能耗定额
    async getEnergyData () {
      this.loading1 = true
      const res = await getEnergyDataApi({
        companyId: this.form.companyId,
        dateString: this.date,
        dateType: this.radio === '月' ? 2 : 3,
        departmentId: this.form.departmentId
      })
      this.EnergyData = res.data?.list
      this.loading1 = false
    },
    async getLine (date) {
      this.loading2 = true
      const res = await getEnergyLineApi({
        companyId: this.form.companyId,
        dateString:
          this.radio === '月'
            ? dayjs(date).format('YYYY-MM-DD')
            : dayjs(date).format('YYYY-MM'),
        dateType: this.radio === '月' ? 1 : 2,
        departmentId: this.form.departmentId
      })
      this.Linelist = res.data?.list
      this.loading2 = false
      if (this.Linelist[0].datalist.length == 0) {
        this.$message({
          message: '暂无数据',
          type: 'warning',
          duration: 1000
        })
      }
      this.myChart1()
    },
    // 能耗指标曲线
    async getEnergyZBLine () {
      this.loading3 = true
      const res = await getEnergyZBLineApi({
        companyId: this.form.companyId,
        dateString: this.date,
        dateType: this.radio === '月' ? 2 : 3,
        departmentId: this.form.departmentId
      })
      this.ZBLinelist = res.data?.list || []
      this.loading3 = false
    },
    // 能耗指标表格
    async getEnergyZBList () {
      this.loading4 = true
      const res = await getEnergyZBListApi({
        companyId: this.form.companyId,
        dateString: this.date,
        dateType: this.radio === '月' ? 2 : 3,
        departmentId: this.form.departmentId,
        departmentName: this.departmentList.find(
          (i) => i.id === this.form.departmentId
        ).departmentName
      })
      this.tableList = res.data.list
      this.loading4 = false
    },
    myChart1 () {
      const data1 = {
        name: this.Linelist[1]?.name,
        type: 'line',
        smooth: true,
        symbol: 'none',
        markPoint: {
          data: [
            {
              type: 'max',
              symbolSize: [70, 60],
              itemStyle: { color: '#5996ff' },
              label: { color: '#000', padding: [5, 10] }
            },
            {
              type: 'min',
              symbolSize: [70, 60],
              itemStyle: { color: '#5996ff' },
              label: { color: '#000', padding: [5, 10] }
            }
          ]
        },
        data:
          this.radio === '月'
            ? this.Linelist[1]?.datalist.map((i) => {
              return [dayjs(i.timeReading).format('HH:mm'), i.valueReading]
            }) || []
            : this.Linelist[1]?.datalist.map((i) => {
              return [
                dayjs(i.timeReading).format('YYYY-MM-DD'),
                i.valueReading
              ]
            }) || [],
        lineStyle: {
          color: '#5996ff'
        },
        areaStyle: {
          normal: {
            // 前四个参数代表位置 左下右上，如下表示从上往下渐变色 暗青色到亮青色，
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#c0d7ff' },
              { offset: 1, color: '#fff' }
            ])
          }
        }
      }
      const data2 = {
        name: this.Linelist[0]?.name,
        type: 'line',
        showSymbol: false,
        lineStyle: {
          color: '#e57373',
          width: 1,
          type: 'dashed'
        },
        data:
          this.radio === '月'
            ? this.Linelist[0]?.datalist.map((i) => {
              return [dayjs(i.timeReading).format('HH:mm'), i.valueReading]
            }) || []
            : this.Linelist[0]?.datalist.map((i) => {
              return [
                dayjs(i.timeReading).format('YYYY-MM-DD'),
                i.valueReading
              ]
            }) || []
      }

      const myChart1 = echarts.init(document.getElementById('nhde'))

      myChart1.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.Linelist.map((i) => i.name),
          right: 30,
          top: 20
        },
        grid: {
          left: '1%',
          right: '2%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timelist
        },
        yAxis: {
          name: 'kWh',
          min: 'dataMin',
          max: 'dataMax',
          axisLine: { show: true },
          splitLine: {
            // 网格线
            lineStyle: {
              type: 'dashed' // 设置网格线类型 dotted：虚线   solid:实线
            },
            show: true // 隐藏或显示
          },
          type: 'value'
        },
        series: [data2, data1]
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart1.resize()
      })
    },
    myChart2 () {
      const data = this.ZBLinelist.map((obj) => {
        return {
          name: obj.name,
          type: 'bar',
          emphasis: {
            focus: 'series'
          },
          data: obj.datalist.map((i) => {
            return [i.timeReading, i.valueReading]
          })
        }
      })
      const myChart2 = echarts.init(document.getElementById('nhzb'))
      myChart2.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category'
          // name: 'kWh/㎡'
          // data: data.map((i) => i.name)
        },
        yAxis: {
          type: 'value',
          name: 'kWh/㎡'
        },
        series: data
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart2.resize()
      })
    },
    async getdatalist () {
      this.getEnergyData()
      this.getEnergyZBList()
      const promises = [
        this.getLine(
          dayjs().format(this.radio === '月' ? 'YYYY-MM-DD' : 'YYYY-MM')
        ).then(() => this.myChart1()),
        this.getEnergyZBLine().then(() => this.myChart2())
      ]
      // 等待所有Promise完成
      await Promise.all(promises)
    },

    chaxun () {
      this.getdatalist()
    },
    async chongzhi () {
      await this.getCompanyList()
      await this.getDepartmentList()
      this.radio = '月'
      this.date = dayjs().format('YYYY-MM-DD')
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 40px;
  .box-item {
    width: 100px;
    height: 90px;
    border: 1px solid #000;
    display: flex;
    justify-content: center;
    align-items: center;
    .box-items {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }
}

.one {
  background-color: red;
  color: #fff;
}
.two {
  background-color: #5dad77;
  color: #fff;
}
.thr {
  background-color: none;
}
::v-deep .prev {
  width: 100%;
  height: 100%;
  text-align: center;
  pointer-events: none;
  .el-calendar-day {
    visibility: hidden;
  }
}
::v-deep .next {
  width: 100%;
  height: 100%;
  text-align: center;
  pointer-events: none;
  .el-calendar-day {
    visibility: hidden;
  }
}
::v-deep .current {
  width: 100%;
  height: 100%;
  text-align: center;
}
.dateCell {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .el-calendar__header {
  display: none;
}
::v-deep .el-calendar__body {
  padding: 0;
}
::v-deep .el-calendar-day {
  height: 30px;
  padding: 0;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-form-item {
  width: 100%;
  margin-left: -10px;
}
::v-deep .el-form-item__content {
  width: calc(100% - 100px);
}
::v-deep .el-col-6 {
  height: 40px;
  text-align: right;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep.el-form--inline {
  height: 100% !important;
  box-sizing: border-box;
}
::v-deep .el-radio-button__inner {
  padding: 8px 20px;
}
::v-deep .el-input__icon {
  line-height: 20px;
}

.bigbox {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  padding: 10px;
  .top {
    background-color: #fff;
    padding: 20px 20px 20px 50px;
    box-sizing: border-box;
    height: 80px;
    width: 100%;
    margin-bottom: 10px;
    // transition-property: all;
    // transition-duration: 0.2s;

    .button {
      width: 63px;
      height: 32px;
      background-color: #fff;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
    .chaxun {
      background-color: #1890ff;
      color: #fff;
    }
  }
  .nhde {
    display: flex;
    width: 100%;
    height: 300px;
    background-color: #fff;
    .left {
      width: 600px;
      height: 300px;
      .tit {
        display: flex;
        justify-content: space-between;
        padding: 10px;
        .mes {
          display: flex;
          .m {
            display: flex;
            align-items: center;
            justify-content: space-around;
            font-size: 13px;
            margin-right: 10px;
            .color {
              width: 15px;
              height: 15px;
              border-radius: 5px;
              margin-right: 10px;
            }
            .color1 {
              background-color: #5dad77;
            }
            .color2 {
              background-color: red;
            }
          }
        }
      }
    }
    .right {
      flex: 1;
      height: 300px;
    }
  }
  .nhzb {
    flex: 2;
    margin-top: 10px;
    width: 100%;
    height: 100%;
    padding: 10px;
    background-color: #fff;
    .toptit {
      display: flex;
      justify-content: space-between;
    }
    .bar {
      width: 100%;
      height: 50%;
    }
  }
}
</style>
